package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.service.impl.AlertRuleServiceImpl;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlerJob {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AlertRuleService alertRuleService;

    //@Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        //查询所有报警规则，如果为空程序结束
        List<AlertRule> allAlerts = alertRuleMapper.selectByFunctionId(null, null, null);
        if (CollUtil.isEmpty(allAlerts)) {
            return;
        }
        //查询所有上报的数据，如果为空程序结束
        List<Object> jsonStrList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if (CollUtil.isEmpty(jsonStrList)) {
            return;
        }
        //设备上报数据不为空，提取设备上报数据为list
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonStrList.forEach(json -> deviceDataVoList.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class)));
        //对每一条设备上报数据进行报警规则校验
        deviceDataVoList.forEach(d ->alertRuleService.alertFilter(d));
    }



}
